package com.bilgeadam.customtags;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author Bora SAYINER
 * @since Jan 18, 2015 6:58:38 PM
 * @version 1.0
 */
public class ComboBoxTag extends SimpleTagSupport implements DynamicAttributes {

	private List items;
	private int selectedIndex;

	private final Map<String, Object> attributes;

	public ComboBoxTag() {
		this.attributes = new HashMap<String, Object>();
		selectedIndex = 0;
	}

	@Override
	public void doTag() throws JspException, IOException {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<select ");
		Set<Entry<String, Object>> entrySet = attributes.entrySet();
		for (Entry<String, Object> entry : entrySet) {
			stringBuilder.append(entry.getKey() + "='" + entry.getValue() + "' ");
		}
		{
			for (int i = 0; i < items.size(); i++) {
				Object item = items.get(i);
				if (i == selectedIndex) {
					stringBuilder.append(String.format("<option value=%s selected>%s</option>", item.toString().toLowerCase(), item));
				} else {
					stringBuilder.append(String.format("<option value=%s>%s</option>", item.toString().toLowerCase(), item));
				}
			}

		}
		stringBuilder.append("></select>");
		getJspContext().getOut().print(stringBuilder.toString());
	}

	public List getItems() {
		return items;
	}

	public void setItems(List items) {
		this.items = items;
	}

	public int getSelectedIndex() {
		return selectedIndex;
	}

	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
	}

	@Override
	public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {
		attributes.put(localName, value);
	}
}
